package com.aegis.common.web.xss;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author wuweixin
 *
 * @Version 1.0
 * @Descritube
 */
//@JsonComponent // 这个是全局json反序列化，不建议直接用
@Component
public class JsoupSanitizingDeserializer extends JsonDeserializer<String> {

    private static final Logger log = LoggerFactory.getLogger(JsoupSanitizingDeserializer.class);

    // Inject the globally configured Safelist bean
    private final Safelist safelist;

    @Autowired
    public JsoupSanitizingDeserializer(Safelist customSafelist) {
        this.safelist = customSafelist;
        log.info("JsoupSanitizingDeserializer initialized.");
    }

    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String originalValue = p.getValueAsString();
        if (originalValue == null || originalValue.isEmpty()) {
            return originalValue;
        }

        if (this.safelist == null) {
            log.warn("Jsoup Safelist is null in JsoupSanitizingDeserializer. Returning original value.");
            return originalValue; // Or throw an exception if this is critical
        }

        String sanitizedValue = Jsoup.clean(originalValue, this.safelist);

        if (log.isTraceEnabled() && !originalValue.equals(sanitizedValue)) {
            log.trace("Sanitized value: original='{}', sanitized='{}'", originalValue, sanitizedValue);
        } else if (!originalValue.equals(sanitizedValue)) {
            log.debug("Sanitized value for field [{}].", p.currentName()); // Log field name if available
        }


        return sanitizedValue;
    }
}